const fs = require('fs')
/**
   *
   * @param {*当前页要显示的数量} pageSize
   * @param {*当前页} currentPage
   * @param {*所有产品数组} arr
   * @returns {*当前页要显示的产品数组} newArr
   */
function pagination (pageSize, currentPage, arr) {
  const skipNum = (currentPage - 1) * pageSize
  const newArr = (skipNum + pageSize >= arr.length) ? arr.slice(skipNum, arr.length) : arr.slice(skipNum, skipNum + pageSize)
  return newArr
}

/**
 *
 * @param {*排序的属性} attr
 * @param {*true为升 false为降} rev
 *
 */

function sortBy (attr, rev) {
  if (rev === undefined) {
    rev = 1
  } else {
    rev = rev ? 1 : -1
  }
  return function (a, b) {
    a = a[attr]
    b = b[attr]
    if (a < b) {
      return rev * -1
    }
    if (a > b) {
      return rev * 1
    }
    return 0
  }
}
function range (arr, gt, lte) {
  return arr.filter(item => item.salePrice >= gt && item.salePrice <= lte)
}

const cors = require('cors')
const jwt = require('jsonwebtoken')
const bodyParser = require('body-parser')
const cartListJSON = require('./serve/db/cartList.json')

// 创建后台数据接口
module.exports = {
  devServer: {
    before (app, serve) {
      app.use(cors())
      app.use(bodyParser.json())
      app.use(bodyParser.urlencoded({ extended: false }))
      // 显示主页数据
      app.get('/api/goods/home', (req, res) => {
        fs.readFile('./serve/db/home.json', 'utf8', (err, data) => {
          if (!err) {
            res.json(JSON.parse(data))
          }
        })
      })

      // 显示全部商品
      app.get('/api/goods/allGoods', (req, res) => {
        // 获取前端地址栏上的查询参数
        const page = parseInt(req.query.page)
        const size = parseInt(req.query.size)
        const sort = parseInt(req.query.sort)
        const gt = parseInt(req.query.priceGt)
        const lte = parseInt(req.query.priceLte)
        const cid = req.query.cid
        let newData = []
        fs.readFile('./serve/db/allGoods.json', 'utf8', (err, data) => {
          const { result } = JSON.parse(data)
          let allData = result.data
          // 过滤，选择价格区间
          if (gt && lte) {
            allData = range(allData, gt, lte)
          }
          // 品牌周边分栏
          if (cid === '1184') {
            allData = allData.filter((item) => item.productName.match(RegExp('Smartisan', 'ig')))
            // 分页显示
            newData = pagination(size, page, allData)
            if (sort === 1) { // 由低到高
              newData = newData.sort(sortBy('salePrice', true))
            } else if (sort === -1) {
              newData = newData.sort(sortBy('salePrice', false))
            }
          } else {
            // 分页显示
            newData = pagination(size, page, allData)
            if (sort === 1) {
              newData = newData.sort(sortBy('salePrice', true))
            } else if (sort === -1) {
              newData = newData.sort(sortBy('salePrice', false))
            }
          }
          res.json({
            data: newData,
            total: allData.length
          })
        })
      })

      // 显示商品详情的数据
      app.get('/api/goods/productDet', (req, res) => {
        const productId = req.query.productId
        fs.readFile('./serve/db/goodsDetail.json', 'utf8', (err, data) => {
          if (!err) {
            const { result } = JSON.parse(data)
            const newData = result.find(item => item.productId == productId)
            res.json(newData)
          }
        })
      })

      // 模拟一个登录的接口
      app.post('/api/login', (req, res) => {
        const username = req.body.user
        res.json({
          // 进行加密的方法
          // sing 参数一：加密的对象  参数二：加密的规则
          token: jwt.sign({ username: username }, 'abcd', {
            // 过期时间
            expiresIn: '3000s'
          }),
          username,
          state: 1,
          file: '/static/images/1570600179870.png',
          code: 200,
          address: null,
          balance: null,
          description: null,
          email: null,
          message: null,
          phone: null,
          points: null,
          sex: null,
          id: 62
        })
      })

      // 登录持久化验证接口，访问这个接口时一定要访问token
      // 先访问登录接口得到token再访问这个，查看是否成功
      app.post('/api/validate', function (req, res) {
        const token = req.headers.authorization
        // 验证token合法性，对token进行解码
        jwt.verify(token, 'abcd', function (err, decode) {
          if (err) {
            res.json({
              msg: '当前用户未登录'
            })
          } else {
            // 证明用户已经登录
            res.json({
              token: jwt.sign({ username: decode.username }, 'abcd', {
                expiresIn: '3000s'
              }),
              username: decode.username,
              msg: '已登录',
              state: 1,
              file: '/static/images/1570600179870.png',
              code: 200,
              address: null,
              balance: null,
              description: null,
              email: null,
              message: null,
              phone: null,
              points: null,
              sex: null,
              id: 62
            })
          }
        })
      })

      // 购物车添加接口,写入添加商品
      app.post('/api/addCart', (req, res) => {
        const { userId, productId, productNum } = req.body
        fs.readFile('./serve/db/allGoods.json', 'utf8', (err, data) => {
          const { result } = JSON.parse(data)
          if (productId && userId) {
            // 找到对应的用户
            const { cartList } = cartListJSON.result.find(item => item.id == userId)
            // 找到对应的商品
            const newData = result.data.find(item => item.productId == productId)
            newData.limitNum = 100

            let falg = true
            if (cartList && cartList.length) {
              cartList.forEach(item => {
                // 寻找添加的商品是否已经存在购物车中
                if (item.productId === productId) {
                  if (item.productNum >= 1) {
                    falg = false
                    item.productNum += parseInt(productNum)
                  }
                }
              })
            }
            // 如果商品不存在，则添加进去
            if (!cartList.length || falg) {
              newData.productNum = parseInt(productNum)
              cartList.push(newData)
            }
            // 序列化， 更新替换cartList.json内容
            fs.writeFile('./serve/db/cartList.json', JSON.stringify(cartListJSON), (err) => {
              if (!err) {
                res.json({
                  code: 200,
                  message: 'success',
                  result: 1,
                  success: true,
                  timestamp: 1571296313981
                })
              }
            })
          }
        })
      })

      app.post('/api/cartList', (req, res) => {
        const { userId } = req.body
        fs.readFile('./serve/db/cartList.json', (err, data) => {
          const { result } = JSON.parse(data)
          const newData = result.find(item => item.id == userId)
          res.json({
            code: 200,
            cartList: newData,
            success: true,
            message: 'success'
          })
        })
      })
    }
  }
}
